<template>
  <el-dialog
      v-model="dialogVisible"
      title="选择商品"
      width="800px"
      :before-close="handleClose"
      class="SalesProductSelect"
  >
    <div class="SalesProductSelect-search">
      <el-input
          v-model="searchForm.name"
          placeholder="输入商品名称搜索"
          class="SalesProductSelect-search-input"
          clearable
      />
      <el-tree-select
          v-model="searchForm.categoryId"
          :data="categoryTreeData"
          :render-after-expand="false"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          class="SalesProductSelect-search-tree"
          placeholder="选择分类"
          check-strictly
          clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <el-table
        :data="tableData.list"
        v-loading="loading"
        class="SalesProductSelect-table"
        border
        stripe
        @row-dblclick="handlePick"
    >
      <el-table-column type="index" width="60" align="center"/>
      <el-table-column prop="code" label="编号" width="120" align="center"/>
      <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
      <el-table-column prop="brand" label="品牌" width="120" align="center">
        <template #default="{ row }">{{ row.brand || '-' }}</template>
      </el-table-column>
      <el-table-column prop="model" label="型号/规格" width="140" align="center">
        <template #default="{ row }">{{ row.model || '-' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handlePick(row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="SalesProductSelect-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="tableData.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="SalesProductSelect-pagination-main"
      />
    </div>

    <template #footer>
      <div class="SalesProductSelect-footer">
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {listProducts} from '../api/productApi.js'
import {getCategoriesTree} from '../api/categoryApi.js'

const props = defineProps({visible: {type: Boolean, default: false}})
const emits = defineEmits(['update:visible', 'selected'])

const dialogVisible = ref(false)
const searchForm = ref({name: '', categoryId: null})
const categoryTreeData = ref([])
const tableData = ref({list: [], total: 0})
const loading = ref(false)
const pagination = ref({pageNum: 1, pageSize: 10})
const hasSearched = ref(false)

watch(() => props.visible, async v => {
  dialogVisible.value = v
  if (v) await loadCategoryTree()
})
watch(dialogVisible, v => {
  if (!v) emits('update:visible', false)
})

const loadCategoryTree = async () => {
  try {
    const res = await getCategoriesTree()
    if (res && typeof res === 'object' && !Array.isArray(res)) {
      categoryTreeData.value = [res]
    } else if (Array.isArray(res)) {
      categoryTreeData.value = res
    } else {
      categoryTreeData.value = []
    }
  } catch (e) {
    ElMessage.error('加载分类失败')
  }
}

const loadProducts = async () => {
  loading.value = true
  try {
    const data = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      condition: {
        name: searchForm.value.name || '',
        categoryIds: searchForm.value.categoryId || null
      }
    }
    const res = await listProducts(data)
    tableData.value = res || {list: [], total: 0}
  } catch (e) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.pageNum = 1
  hasSearched.value = true
  loadProducts()
}
const handleSizeChange = size => {
  pagination.value.pageSize = size
  pagination.value.pageNum = 1
  if (hasSearched.value) loadProducts()
}
const handleCurrentChange = page => {
  pagination.value.pageNum = page
  if (hasSearched.value) loadProducts()
}

const handlePick = row => {
  if (!row) return
  emits('selected', {id: row.id, code: row.code, name: row.name, unit: row.unit})
}
const handleClose = () => {
  dialogVisible.value = false
}

onMounted(() => {
  hasSearched.value = true
  loadProducts()
})
</script>

<style scoped lang="scss">
.SalesProductSelect {
  &-search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding-bottom: 16px;

    &-input {
      width: 260px;
    }

    &-tree {
      width: 240px;
    }
  }

  &-table {
    width: 100%;
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}
</style>